import Layout from '@/common/layout/Layout.vue';
import {createRouter, createWebHistory, RouteRecordRaw} from "vue-router";
import {useRouteStore} from "@/common/store/modules/route";
import {jsonToUrlParams} from "@/common/util/kit";
//全部组件路径
let components = import.meta.glob("@/module/**/*.vue")
//相对路径
const BASE = '/src/module';

//静态路由
const routeConst: Array<RouteRecordRaw> = [
    {
        path: '/',
        name: "Layout",
        component: Layout,
        redirect: '/index',
        children: [
            {
                path: '/index',
                component: components[`${BASE}/basics/index.vue`],
            },
            {
                path: "/404",
                component: components[`${BASE}/basics/404.vue`],
                meta: {
                    tab_is_close: '1',
                },
            },
        ]
    },
    {
        path: "/login",
        component: components[`${BASE}/basics/login.vue`]
    }
];

//异步加载路由组件
export async function asyncAddRoute(routeList) {
    return new Promise((resolve, reject) => {
        routeList.filter(e => {
            if (e.path && e.path != '#' && e.component_path) {
                //插入动态路由
                router.addRoute("Layout", {
                    name: e.path,
                    path: e.path,
                    component: components[`${BASE}${e.component_path}.vue`]
                })
            }
        })
        resolve(true)
    })

}

//跳转路径并携带路由参数
export function pushAddParam(path) {
    let toRoute = null
    toRoute = useRouteStore().menu.filter(e => {
        if (e.path == path) {
            toRoute = e
        }
    })[0]

    if (toRoute && toRoute.param) {
        let routeParam = jsonToUrlParams(JSON.parse(toRoute.param))
        //console.log("【路由携带原始参数】", toRoute.param)
        //console.log("【转换后参数】", routeParam)
        router.push(`${path}?${routeParam}`).then(r => {
        })
    } else {
        router.push(`${path}`).then(r => {
        })
    }
}

export function push(path) {
    router.push(`${path}`).then(r => {
    })
}


const router = createRouter({
    history: createWebHistory(),
    routes: routeConst
})

export default router;

